package com.lua;


import com.core.ILuaEvent;
import com.google.protobuf.InvalidProtocolBufferException;
import com.helper.Debug;
import com.helper.ReflactionHelper;
import com.proto.TMessage;
import net.sf.json.JSONObject;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.*;

public class LJBridge {



    static HashMap<String,ILuaEvent>  luaEventMap = new HashMap<>();
    public static void  initBridge() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        words = TMessage.Words.newBuilder();
        Set<Class<? extends ILuaEvent>> list = ReflactionHelper.getReflectionClass(ILuaEvent.class,"com.lua.event");

//        CallLua.getInstance().launch("service","core/service");
        Iterator it = list.iterator();
        while (it.hasNext()){
            Class<?> clx = (Class<?>)it.next();
            Constructor<?> cons = clx.getConstructor();
            if (!Modifier.isAbstract(clx.getModifiers())){
                Debug.log(cons.getName().toString());
                Object obj = cons.newInstance();
                String[] arr = obj.getClass().toString().split("\\.");
                luaEventMap.put(arr[arr.length - 1],(ILuaEvent) obj);
            }

        }

    }
    public static void info(String jsonStr){

        JSONObject json = JSONObject.fromObject(jsonStr);
    }

    public static void launch(String file){
        CallLua.getInstance().launch(file);

    }


    static TMessage.Words.Builder words;
    public static String call(String params) throws InvalidProtocolBufferException {
        JSONObject jsonObject = JSONObject.fromObject(params);
        String cmd = jsonObject.getString("cmd");
        String pas = jsonObject.getString("params");
        String reback = "cmd is invalid";
        if(luaEventMap.containsKey(cmd)){
            reback = luaEventMap.get(cmd).doSomething(pas);
        }
        return reback;

    }
}
